<?php
class Communication_Model_Email extends Zen_List {
	
	public function __construct() {
		$this->table = new Communication_Model_DbTable_Email();
	}
	
	public function beforeCreate($params){
		if (! isset ( $params ['from'] )) {
			$cnf = Zend_Registry::get ( 'cnf' );
			$from = "noreply@" . $cnf->domen;
		}
		return $params;
	}
	
	public function send_messages($id = false) {
		$tablelog = new Communication_Model_DbTable_Emaillog();
		if ($id == false)
			$res = $this->table->fetchAll ()->toArray ();
		else
			$res = $this->table->select ()->where ( 'id=?', $id )->query ()->fetchAll ();
		
		if (sizeof ( $res ) > 0) {
			foreach ( $res as $message ) {
				$transport = Zend_Mail::getDefaultTransport();
				$mail = new Zend_Mail ('UTF-8');
				$mail->setBodyHtml ($message ['text']);
				$mail->addTo ( $message ['to'] );
				$mail->setSubject ( $message ['subject'] );
				$sended=false;
				try {
					$sended=$mail->send ($transport);
				}
				catch (Exception $e) {
					//throw $e; 
				}
				if ($sended!=false) {
					
					$data = array ("text" => $message ['text'], "subject" => $message ['subject'], "from" => $message ['from'], "to" => $message ['to'], "ts" => date ( "Y-m-d H:i:s" ) );
					$tablelog->insert ( $data );
					$this->table->delete ( 'id=' . $message ['id'] );
				}
			}
		} else
			return FALSE;
	}

}

?>